import React, { useState, useEffect } from "react";
import styles from "./index.module.less";
// eslint-disable-next-line
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";
import { connect } from "react-redux";
import {
    publishLeaveMessageAction,
    getOneLeaveMessageAction,
    reviseLeaveMessageAction,
} from "@redux/actions02";
import toast from "@utils/showToast";
import { useNavigate, useLocation } from "react-router-dom";

const PublishMessage = (props) => {
    const {
        publishLeaveMessageAction,
        getOneLeaveMessageAction,
        message,
        reviseLeaveMessageAction,
    } = props;
    const navigate = useNavigate();
    const locate = useLocation();
    const [title, setTitle] = useState(
        locate.state && locate.state.id && message ? message.title : ""
    );
    const [md, setMd] = useState(
        locate.state && locate.state.id && message ? message.content : ""
    );

    const publish = () => {
        if (!title.trim()) {
            toast.fail("标题不能为空");
            return;
        }
        if (!md.trim()) {
            toast.fail("内容不能为空");
            return;
        }

        locate.state && locate.state.id
            ? reviseLeaveMessageAction(locate.state.id, title, md, navigate)
            : publishLeaveMessageAction(title, md, navigate);
    };

    useEffect(() => {
        // console.log('locate: ', locate)
        if (locate.state) {
            const { id } = locate.state;
            id && getOneLeaveMessageAction(id);
        }
    }, [locate, getOneLeaveMessageAction]);

    return (
        <div className={styles.publish_message}>
            <input
                type="text"
                placeholder="请输入标题"
                className={styles.title}
                value={title}
                onChange={(e) => {
                    setTitle(e.target.value);
                }}
            />
            <MDEditor
                className={styles.md_editor}
                height={500}
                value={md}
                onChange={setMd}
                previewOptions={{
                    rehypePlugins: [[rehypeSanitize]],
                }}
                visibleDragbar={false}
            />
            <button className={styles.publish_btn} onClick={publish}>
                发布留言
            </button>
        </div>
    );
};

export default connect((state) => ({ message: state.oneLeaveMessageReducer }), {
    publishLeaveMessageAction,
    getOneLeaveMessageAction,
    reviseLeaveMessageAction,
})(PublishMessage);
